import {Component, OnInit} from '@angular/core';
import {BladeContainerBase} from '../../../../shared/blade/blade-container-base';
import {FormBuilder, Validators, FormControl} from '@angular/forms';
import {Observable} from 'rxjs/Observable';
import {Command} from '../../../../shared/toolbar.service';

import {Farm} from '../../../../entity/farm.model';
import {Phase} from '../../../../entity/phase.model';
import {Circuit} from '../../../../entity/circuit.model';
import {Model} from '../../../../entity/model.model';
import {Device} from '../../../../entity/device.model';
import {DeviceCategory} from '../../../../entity/device-category.model';
import {SubArray} from '../../../../entity/subarray.model';

import {FarmService} from '../../../../service/farm.service';
import {PhaseService} from '../../../../service/phase.service';
import {CircuitService} from '../../../../service/circuit.service';
import {ModelService} from '../../../../service/model.service';
import {DeviceService} from '../../../../service/device.service';
import {DeviceCategoryService} from '../../../../service/device-category.service';
import {SubArrayService} from '../../../../service/sub-array.service';


@Component({
  selector: 'app-device-edit',
  templateUrl: './device-edit.component.html',
  styleUrls: ['./device-edit.component.css']
})
export class DeviceEditComponent extends BladeContainerBase<Device> {
  /**
   * 所有风场
   * @private
   * @type {Farm}
   * @memberof DeviceEditComponent
   */
  farms: Farm[] = [];
  /**
   * 所有分期
   * @private
   * @type {Phase}
   * @memberof DeviceEditComponent
   */
  phases: Phase[] = [];
  /**
   * 所有线路
   * @private
   * @type {Circuit}
   * @memberof DeviceEditComponent
   */
  circuits: Circuit[] = [];
  /**
   * 所有型号
   * @private
   * @type {Model}
   * @memberof DeviceEditComponent
   */
  models: Model[] = [];
  /**
   * 所有设备类别
   * @private
   * @type {Model}
   * @memberof DeviceEditComponent
   */
  deviceCagegorys: DeviceCategory[] = []

  /**
   * 所属父级
   * @private
   * @type {Model}
   * @memberof DeviceEditComponent
   */
  public devicesItems: Device[] = [];

  /**
   * 区域集合
   * @private
   * @type {Model}
   * @memberof DeviceEditComponent
   */
  public subArrays: SubArray[] = [];

  controlName: FormControl;

  controlCode: FormControl;

  isShow: boolean;

  constructor(
    private fb: FormBuilder,
    private deviceService: DeviceService,
    private farmService: FarmService,
    private phaseService: PhaseService,
    private circuitService: CircuitService,
    private modelService: ModelService,
    private deviceCategoryService: DeviceCategoryService,
    private subArrayService: SubArrayService,
  ) {
    super(fb);
  }

  ngOnInit() {
    this.initDevice();
    this.isShow = this.parentEntity.isShow;
    //编辑时注册按钮和按钮命令
    if (!this.isNew) {
      this.commands = [
        new Command('save', '保存', 'fa fa-save', 'setofkey:update', (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
        new Command('reset', '重置', 'fa fa-save', 'setofkey:reset', (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
      ]
    }
    else {
      let parentDevice: Device = this.parentEntity.parent;
      this.currentEntity = new Device(0, 2, (this.parentBlade.parentEntity as Phase).farmId, (this.parentBlade.parentEntity as Phase).phaseId, 0, 1, 0, '', '', '', '', 0, false, 0, 0);
      this.currentEntity.parentId = parentDevice ? parentDevice.deviceId : 0;
    }
    super.ngOnInit();
  }

  /**
   * 重新构建菜单
   *
   * @private
   * @memberof MenuEditComponent
   */
  private initDevice() {
    this.devicesItems = [];

    let devices: Device[] = this.parentEntity.devices;

    devices.forEach(device => {
      let deviceItme: Device = new Device(
        device.deviceId,
        device.deviceCategoryId,
        device.farmId,
        device.phaseId,
        device.circuitId,
        device.modelId,
        device.subArrayId,
        device.deviceCode,
        device.deviceName,
        device.longitude,
        device.latitude,
        device.elevation,
        device.turBenchMark,
        device.seq,
        device.parentId
      );
      let name = '|';
      for (let i = 0; i < device.leave; i++) {
        name += '— ';
      }
      deviceItme.deviceName = `${name}${deviceItme.deviceName}`;
      this.devicesItems.push(deviceItme);
    });

  }

  /**
   * 初始化数据
   * @memberof BladeContainerBase
   */
  initData(): any | Observable<any> | Promise<any> {
    this.farmService.getFarms()
      .then(res => {
        this.farms = [...res];
        if (this.isNew) {//添加按钮
          if (this.parentBlade.parentEntity != null) {
            this.currentEntity.farmId = (this.parentBlade.parentEntity as Phase).farmId;
          }
          else {
            if (this.farms.length > 0)
              this.currentEntity.farmId = this.farms[0].farmId;
          }
        }
        this.initPhaseData(this.currentEntity.farmId);
        this.initCircuitDataByFarmId(this.currentEntity.farmId);
        this.initModelData();
        this.initDeviceCategoryData();
        this.initSubArraysData();
        this.formPatchValue(this.currentEntity);
      })
      .catch(error => this.bladeData.error = error)
      .then(res => this.bladeData.isLoading = false);
  }

  /**
   * 通过风场id获取工期
   */
  initPhaseData(farmId: number) {
    this.phaseService.getPhasesByfarmId(farmId)
      .then(res => {
        this.phases = [...res];
        this.formGroup.get('phaseId').setValue(this.currentEntity.phaseId);
      })
      .catch(error => this.bladeData.error = error)
      .then(res => this.bladeData.isLoading = false);

  }

  /**
   * 根据风场id查询线路
   */

  initCircuitDataByFarmId(farmId: number) {
    this.circuitService.getCircuitByFarmId(farmId)
      .then(res => {
        this.circuits = [...res];
        this.formGroup.get('circuitId').setValue(this.currentEntity.circuitId);
      })
      .catch(error => this.bladeData.error = error)
      .then(res => this.bladeData.isLoading = false);
  }

  /**
   * 获取所有型号
   */
  initModelData() {
    this.modelService.getModels()
      .then(res => {
        this.models = [...res];
        this.formGroup.get('modelId').setValue(this.currentEntity.modelId);

      })
      .catch(error => this.bladeData.error = error)
      .then(res => this.bladeData.isLoading = false);
  }

  /**
   * 获取所有型号类别
   */
  initDeviceCategoryData() {
    this.deviceCategoryService.getDeviceCategorys()
      .then(res => {
        this.deviceCagegorys = [...res];
        this.formGroup.get('deviceCategoryId').setValue(this.currentEntity.deviceCategoryId);

      })
      .catch(error => this.bladeData.error = error)
      .then(res => this.bladeData.isLoading = false);
  }

  /**
   * 获取所有分区
   */
  initSubArraysData() {
    this.subArrayService.getSubArrays()
      .then(res => {
        this.subArrays = [...res];
      })
      .catch(error => this.bladeData.error = error)
      .then(res => this.bladeData.isLoading = false);
  }

  exeSaveChange(blade: any): void {
    this.saveChange();
  }

  canSaveChange(blade: any): boolean {
    // console.log(this.hasChange())
    // console.log(!this.hasError())
    return this.hasChange() && !this.hasError();
  }

  exeReset(blade: any): void {
    return this.formGroup.reset(this.currentEntity);
  }

  canReset(blade: any): boolean {
    return this.hasChange();
  }

  /**
   * 创建表单
   *
   *
   * @memberof TurbineEditComponent
   */
  createForm() {

    this.formGroup = this.fromBuider.group({
      'parentId': [this.currentEntity.parentId, [
        Validators.pattern('[0-9]{1,5}'),
        Validators.maxLength(5)
      ]],
      'farmId': [this.currentEntity.farmId, [
        Validators.required,
        Validators.pattern('[0-9]{1,5}'),
        Validators.maxLength(5)
      ]],
      'phaseId': [this.currentEntity.phaseId, [
        Validators.required,
        Validators.pattern('[0-9]{1,5}'),
        Validators.maxLength(5)
      ]],
      'circuitId': [this.currentEntity.circuitId, [
        Validators.required,
        Validators.pattern('[0-9]{1,5}'),
        Validators.maxLength(5)
      ]],
      'modelId': [this.currentEntity.modelId, [
        Validators.required,
        Validators.pattern('[0-9]{1,5}'),
        Validators.maxLength(5)
      ]],
      'deviceCode': [this.currentEntity.deviceCode, [
        Validators.required,
        Validators.maxLength(20)
      ], (control: FormControl): any => this.deviceCodeAsnyValidator(control)],// (control: FormControl): any => this.deviceCodeAsnyValidator(control)
      'deviceName': [this.currentEntity.deviceName, [//??????????????????????
        Validators.required,
        Validators.pattern('^#[\u4e00-\u9fa5_a-zA-Z0-9]{1,20}'),
        Validators.maxLength(20)
      ], (control: FormControl): any => this.deviceNameAsnyValidator(control)],// (control: FormControl): any => this.deviceNameAsnyValidator(control)
      'deviceCategoryId': [this.currentEntity.deviceCategoryId, [
        Validators.required,
        Validators.pattern('[0-9]{1,5}'),
        Validators.maxLength(5)
      ]],
      'subArrayId': [this.currentEntity.subArrayId, [
        Validators.required,
        Validators.pattern('[0-9]{1,5}'),
        Validators.maxLength(5)
      ]],
      'seq': [this.currentEntity.seq, [
        Validators.required,
        Validators.pattern('[0-9]{1,5}'),
        Validators.maxLength(5)
      ]],
      'longitude': [this.currentEntity.longitude, [
        Validators.maxLength(20)
      ]],
      'latitude': [this.currentEntity.latitude, [
        Validators.maxLength(20)
      ]],
      'elevation': [this.currentEntity.elevation, [
        Validators.maxLength(7)
      ]],
      'turBenchMark': [this.currentEntity.turBenchMark, [
        // Validators.required
      ]]

    });
  }

  /**
   * 设置表单错误对象
   *
   *
   * @memberof BladeContainerBase
   */
  setFormError(): void {
    this.formErrors = {
      'parentId': '',
      'farmId': '',
      'phaseId': '',
      'circuitId': '',
      'modelId': '',
      'deviceCode': '',
      'deviceName': '',
      'deviceCategoryId': '',
      'subArrayId': '',
      'seq': '',
      'longitude': '',
      'latitude': '',
      'elevation': '',
      'turBenchMark': ''
    };
  }

  /**
   * 设置表单验证信息
   *
   *
   * @memberof BladeContainerBase
   */
  setValidationMessages(): void {
    this.validationMessages = {

      'parentId': {
        'required': '不能为空。',
        'pattern': '由数字组成。',
        'maxlength': '不能多于5个字符长度。',
      },
      'farmId': {
        'required': '不能为空。',
        'pattern': '由数字组成。',
        'maxlength': '不能多于5个字符长度。',
        'exist': '已存在。',
      },
      'phaseId': {
        'required': '不能为空。',
        'pattern': '由数字组成。',
        'maxlength': '不能多于5个字符长度。',
        'exist': '已存在。',
      },
      'circuitId': {
        'required': '不能为空。',
        'pattern': '由数字组成。',
        'maxlength': '不能多于5个字符长度。',
        'exist': '已存在。',
      },
      'modelId': {
        'required': '不能为空。',
        'pattern': '由数字组成。',
        'maxlength': '不能多于5个字符长度。',
        'exist': '已存在。',
      },
      'deviceCode': {
        'required': '不能为空。',
        'maxlength': '不能多于20个字符长度。',
        'exist': '已存在。',
      },
      'deviceName': {
        'required': '不能为空。',
        'pattern': '格式不正确',
        'maxlength': '不能多于20个字符长度。',
        'exist': '已存在。',
      },
      'deviceCategoryId': {
        'required': '不能为空。',
        'pattern': '由数字组成。',
        'maxlength': '不能多于5个字符长度。',
      },
      'subArrayId': {
        'pattern': '由数字组成。',
        'maxlength': '不能多于5个字符长度。',
      },
      'seq': {
        'pattern': '由数字组成。',
        'maxlength': '不能多于5个字符长度。',
      },
      'longitude': {
        'required': '不能为空。',
        'pattern': '由数字组成。',
        'maxlength': '不能多于20个字符长度。',
        'exist': '已存在。',
      },
      'latitude': {
        'required': '不能为空。',
        'pattern': '由数字组成。',
        'maxlength': '不能多于20个字符长度。',
        'exist': '已存在。',
      },
      'elevation': {
        'required': '不能为空。',
        'pattern': '由数字组成。',
        'maxlength': '不能多于7个字符长度。',
      },
      'turBenchMark': {
        // 'required': '不能为空。',
      }

    };
  }

  // 创建按钮
  onCreate() {
    if (!this.hasError()) {
      this.bladeData.isLoading = true;
      let formValue = this.formGroup.value;
      this.currentEntity.parentId = formValue.parentId;
      this.currentEntity.farmId = formValue.farmId;
      this.currentEntity.phaseId = formValue.phaseId;
      this.currentEntity.farmId = formValue.farmId;
      this.currentEntity.circuitId = formValue.circuitId;
      this.currentEntity.modelId = formValue.modelId;
      this.currentEntity.deviceCode = formValue.deviceCode;
      this.currentEntity.deviceName = formValue.deviceName;

      this.currentEntity.deviceCategoryId = formValue.deviceCategoryId;
      this.currentEntity.subArrayId = formValue.subArrayId;
      this.currentEntity.seq = formValue.seq;

      this.currentEntity.longitude = formValue.longitude;
      this.currentEntity.latitude = formValue.latitude;
      this.currentEntity.elevation = formValue.elevation;
      this.currentEntity.turBenchMark = formValue.turBenchMark;
      this.deviceService.create(this.currentEntity)
        .then(res => {
          if (res) {
            let parentContainerInstance = this.parentBlade.bladeContainerInstance;
            parentContainerInstance.refresh(res);
            this.bladeService.closeBlade(this.currentBlade);
          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }

  saveChange(): any | Promise<any> | Observable<any> {
    if (this.canSaveChange(this.currentBlade)) {
      this.bladeData.isLoading = true;
      let formValue = this.formGroup.value;
      this.currentEntity.parentId = formValue.parentId;
      this.currentEntity.farmId = formValue.farmId;
      this.currentEntity.phaseId = formValue.phaseId;
      this.currentEntity.farmId = formValue.farmId;
      this.currentEntity.circuitId = formValue.circuitId;
      this.currentEntity.modelId = formValue.modelId;
      this.currentEntity.deviceCode = formValue.deviceCode;
      this.currentEntity.deviceName = formValue.deviceName;

      this.currentEntity.deviceCategoryId = formValue.deviceCategoryId;
      this.currentEntity.subArrayId = formValue.subArrayId;
      this.currentEntity.seq = formValue.seq;

      this.currentEntity.longitude = formValue.longitude;
      this.currentEntity.latitude = formValue.latitude;
      this.currentEntity.elevation = formValue.elevation;
      this.currentEntity.turBenchMark = formValue.turBenchMark;
      return this.deviceService.update(this.currentEntity)
        .then(res => {
          if (res) {
            (this.parentBlade.bladeContainerInstance).refresh(res);
            this.bladeService.closeBlade(this.currentBlade);
            return true;
          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }

  deviceCodeAsnyValidator(control: FormControl): any {
    this.controlCode = control;
    if (!control.value || control.value == this.currentEntity.deviceCode) {
      return Observable.of(null);
    }
    return this.deviceService.hasDeviceCode(control.value, this.currentEntity.deviceId, this.currentEntity.farmId, this.currentEntity.deviceCategoryId)
      .map(res => res ? {exist: true} : null);
  }


  deviceNameAsnyValidator(control: FormControl): any {
    this.controlName = control;

    if (!control.value || control.value == this.currentEntity.deviceName) {
      return Observable.of(null);
    }
    return this.deviceService.hasDeviceName(control.value, this.currentEntity.deviceId, this.currentEntity.farmId, this.currentEntity.deviceCategoryId)
      .map(res => res ? {exist: true} : null);
  }


  onDeviceCategoryChange(deviceCategoryId: number) {
    this.currentEntity.deviceCategoryId = deviceCategoryId;
    if (this.controlName != undefined) {
      this.deviceNameAsnyValidator(this.controlName);
    }
    if (this.controlCode != undefined) {
      this.deviceCodeAsnyValidator(this.controlCode);
    }
    ;

  }

  onFarmChange(farmId: number) {
    this.currentEntity.farmId = farmId;
  }

}


// WEBPACK FOOTER //
// ./src/app/module/basic/device/device-edit/device-edit.component.ts
